package com.indicator.server.controller;


import com.indicator.base.conf.RedisConfig;
import com.indicator.base.constant.ControllerConstants;
import com.indicator.server.controller.parameter.IndicatorParameter;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.indicator.base.constant.ControllerConstants.*;


@RestController()
@RequestMapping(INDICATOR)
public class IndicatorController {

    @PostMapping(ControllerConstants.ADD)
    public String addIndicator(@RequestBody IndicatorParameter indicatorParameter) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        Object obj = redisCommands.get(indicatorParameter.getKey());
        if (obj == null) {
            redisCommands.set(indicatorParameter.getKey(), indicatorParameter.getValue());
            return ControllerConstants.OK;
        }
        return ControllerConstants.EXITS;
    }

    /**
     * 通知到订阅的客户端
     * @param indicatorParameter
     * @return
     */
    @PostMapping(UPDATE)
    public String updateIndictor(@RequestBody IndicatorParameter indicatorParameter) {
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        String key = INDICATOR_REDIS+indicatorParameter.getKey();
        redisCommands.hset(key, COMPUTE_TYPE_KEY, indicatorParameter.getType());
        redisCommands.hset(key, COMPUTE_TYPE_DEFAULT_VALUE, indicatorParameter.getValue());
        redisCommands.hset(key, IS_COMPUTE, indicatorParameter.getIsCompute());
        redisCommands.hset(key, COMPUTE_SUB_KEY, indicatorParameter.getKey());
        return OK;
    }

    @DeleteMapping(DELETE + DIAGONAL + KEY+"/{subKey}")
    public String deleteIndictor(@PathVariable String key,@PathVariable String subKey) {
        if(subKey.equals("-1")){
            RedisConfig.getInstance().get().zrem(key);
        }else {
            RedisConfig.getInstance().get().zrem(key,subKey);
        }
        return OK;
    }

    @GetMapping(GET + DIAGONAL + KEY)
    public Map<String, Object> getIndictor(@PathVariable String key) {
        return RedisConfig.getInstance().get().hgetall(key);
    }

}
